package com.xiaomage.aidlserver

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private val TAG="AIDL--服务端：MainActivity"
    private var iAidlService:IAidlService?=null
    private val mServiceConnection=object:ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {
            Log.i(TAG,"onServiceDisconnected")
            iAidlService=null
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.i(TAG,"onServiceDisconnected")
            //获取service对象
            iAidlService= IAidlService.Stub.asInterface(service)
            Log.i(TAG,"绑定成功")
        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val pid=android.os.Process.myPid()
        Log.d(TAG,"pid:$pid")
        tv_content.setOnClickListener{
            //点击第二次的时候次可以改变TextView的值，因为第一次只是绑定，返回的对象是空。
            //启动服务
           // val service = Intent(IAidlService::class.java.name)
            //intent=Intent(this,IAidlService::class.java)
            intent=Intent(this,AidlService::class.java)
            bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE)
            Log.e(TAG,iAidlService.toString())
            if(iAidlService!=null){
                tv_content.text=iAidlService?.value
            }

        }
    }
    override fun onDestroy() {
        super.onDestroy()
        unbindService(mServiceConnection)
    }
}
